package top.tagao.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import top.tagao.yygh.cmn.listener.DictListener;
import top.tagao.yygh.cmn.mapper.DictMapper;
import top.tagao.yygh.cmn.service.DictService;
import top.tagao.yygh.model.cmn.Dict;
import top.tagao.yygh.vo.cmn.DictEeVo;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author fu-xiao-liu
 * @Date 2022/3/1 14:30
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

    //根据数据id查询子数据列表
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(queryWrapper);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            dict.setHasChildren( isChildren(dictId));
        }
        return dictList;
    }


    // 导出数据字典
    @Override
    public void exportDict(HttpServletResponse response) {
        // 设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        //查询数据库
        List<Dict> listDict = baseMapper.selectList(null);
        //Dict -- DictEeVo
        List<DictEeVo> dictVoList = new ArrayList<>();
        for (Dict dict : listDict) {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict, dictEeVo);
            dictVoList.add(dictEeVo);
        }

        //调用方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("dict")
                    .doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void importDictData(MultipartFile file) {

    }

    /**
     * @date  根据上级编码与值获取数据字典名称
     */
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public String getDictName(String dictCode, String value) {
        //如果value能唯一定位数据字典，parentId可以传空，例如：省市区的value值能够唯一确定
        if (StringUtils.isEmpty(dictCode) ){
            //直接根据value查询
            Dict dict = dictMapper.selectOne(new QueryWrapper<Dict>().eq("value",value));
            if(null != dict) {
                return dict.getName();
            }
        }else {
            Dict parentDict = this.getDictByDictCode(dictCode);
            if(null == parentDict) return "";
            Dict dict = dictMapper.selectOne(new QueryWrapper<Dict>().eq("parent_id", parentDict.getId()).eq("value", value));
            if(null != dict) {
                return dict.getName();
            }
        }

        return "";

    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict codeDict = this.getDictByDictCode(dictCode);
        if(null == codeDict) return null;
        return this.findChildData(codeDict.getId());
    }

    private Dict getDictByDictCode(String parentId) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",parentId);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }


    // 判断是否存在子节点
    public boolean isChildren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = dictMapper.selectCount(wrapper);
        return  count > 0 ;
    }
}
